package com.lsk.internalcommon.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lsk.internalcommon.request.TokenRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {

    //盐
    private static final String SIGN = "lsk123465";
    private static final String TOKEN_KEY_PHONE = "passenger";
    private static final String TOKEN_KEY_IDENTITY = "identity";
    private static final String TOKEN_TYPE = "token_type";
    private static final String TOKEN_TIME = "token_time";

    //生成jwt
    public static String generatorToken(String passenger,String identity,String tokenType){
        HashMap<String, String> map = new HashMap<>();
        map.put(TOKEN_KEY_PHONE,passenger);
        map.put(TOKEN_KEY_IDENTITY,identity);
        map.put(TOKEN_TYPE,tokenType);

        //token过期时间
//防止token一样，加一个时间戳
        map.put(TOKEN_TIME,Calendar.getInstance().getTime().toString());

        JWTCreator.Builder builder = JWT.create();

        //整合map
        map.forEach(
                (k,v) ->{
                    builder.withClaim(k,v);
                }
        );

        //整合过期时间
//        builder.withExpiresAt(time);
        //生成token
        String sign = builder.sign(Algorithm.HMAC256(SIGN));
        return sign;
    }


    //解析jwt
    public static TokenRequest parseToken(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        String phone = verify.getClaim(TOKEN_KEY_PHONE).asString();
        String identity = verify.getClaim(TOKEN_KEY_IDENTITY).asString();

        TokenRequest tokenRequest = new TokenRequest();
        tokenRequest.setPhone(phone);
        tokenRequest.setIdentity(identity);
        return tokenRequest;
    }

    //校验token，校验token是否异常
    public static TokenRequest checkToken(String token){
        TokenRequest tokenRequest = null;
        try {
            tokenRequest=JwtUtils.parseToken(token);
        }catch (Exception e){

        }
        return tokenRequest;
    }
}
